var express = require('express');
var router = express.Router();
var dbcomm = require('./util/dbcomm');
var util = require("util");
var bodyParser = require("body-parser");

var router = express.Router();//目标:路由文件，可以提供给express使用

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended:false }));
var urlencodedParser = bodyParser.urlencoded({ extended: false })

router.get("/skip",function(req,res){
    res.redirect("../../daily/menuTree.html")
});

router.get("/treecs",function(req,res){
    var sql = "select * from sys_menu";
    dbcomm.query(sql,function(err,data){
        if(err)throw err;
        else{

            res.send(findRows(-1,data))
        }
    })

})


/**
 * 判断当前节点是否存在子节点 
 */
function isCheck(id,tt){
	var ist = false;
	for(var i = 0 ;i < tt.length;i++){
		if(id == tt[i].pmenuid){
			ist = true;
			break;
		}
	}
	return ist;;
}

function findRows(id,dt){
	var arr = [];
	for(var i = 0 ;i < dt.length;i++){				
		if(id == dt[i].pmenuid){
			var first= {
				id : dt[i].menuid,
				text : dt[i].menuname,
			}				
			if(isCheck(dt[i].menuid,dt)){
				first["children"] = findRows( dt[i].menuid,dt);
			}
			arr[arr.length] = first;
		}
	}  
	return arr;		
}
 
router.post('/inMenu', urlencodedParser, function (req, res) {
    var body = req.body;
    dbcomm.query("insert into sys_menu (menuname,menuurl,pmenuid,micon) values(?,?,?,?)",[body.menuname,body.menuurl,body.pmenuid,body.micon],function (data){
          res.send(data);
    });
});
 


//开发成模块
module.exports = router;